//
//  SampuxEquipDetailViewController.m
//  Sampux
//
//  Created by rzm on 16/7/5.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxEquipDetailViewController.h"
#import "SampuxEquipmentDetailView.h"
#import "SPEquipmentInstallViewController.h"
#import "SPGetDeviceDetailValue.h"
#import "SmapuxSettingUnitButton.h"
#import "MJRefreshStateHeader.h"
#import "SampuxGetCurrentTime.h"

@interface SampuxEquipDetailViewController ()
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *titleLab ;
@property (nonatomic, strong) SmapuxSettingUnitButton *antifreezingBtn;
@property (nonatomic, strong) UIScrollView *stateOffView;
@property (nonatomic, strong) MJRefreshStateHeader *header;
@property (nonatomic, strong) UIScrollView *backView;
@property(nonatomic,assign) BOOL isConnectOrNot;
@property (nonatomic, strong) UIActivityIndicatorView *activity;
@property (nonatomic, strong) UIImageView *backImageView ;

@end

@implementation SampuxEquipDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isConnectOrNot = YES;

    [self.navigationItem setHidesBackButton:YES];
    _backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:_backImageView];
    _backImageView.userInteractionEnabled = YES;
    _backImageView.image = imageNamed(@"backImg");
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStatus:) name:NOTIFICATION_RESPONSE_DEVICE_STATUS_13001 object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNewStatus:) name:NOTIFICATION_PUSH_DEVICE_STATUS_13001 object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setTitle:) name:@"setEquipAlisa" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestSwitch:) name:NOTIFICATION_RESPONSE_SET_POWERSWITCH object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestWorkMode:) name:NOTIFICATION_RESPONSE_SET_WORKMODE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestHeatMode:) name:NOTIFICATION_RESPONSE_SET_HEATMODE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setTemp:) name:NOTIFICATION_RESPONSE_SET_TEMPE object:nil];

    [GBInterMaster_CommForDeivce requestDeviceStatus:0 withDeviceAccount:self.detailModel.accountStr];

}


- (void)createAddBarBtnItem
{
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
    UIButton *rightBtn = [UIButton createButton];
    [rightBtn setImage:imageNamed(@"setting") forState:UIControlStateNormal];
    self.rightBtn = rightBtn;
    rightBtn.frame = CGRectMake(kScreenWidth - 10 - 40, 20, 40, 40);
    [rightBtn addTarget:self action:@selector(settingBarBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_nav.img addSubview:self.rightBtn];
}

- (void)setDevice:(GBInterMaster_Bean_DeviceInfo13001 *)device
{
    _device = device;
//    [self getData:_device];
}


- (void)setDetailModel:(SampuxListModel *)detailModel
{
    _detailModel = detailModel;
}

- (void)createDetailView
{
    _detailView = [[SampuxEquipmentDetailView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    _detailView.titleStr = self.titleStr;
    [self.view addSubview:_detailView];
    _detailView.model = [SPGetDeviceDetailValue getDetailData:self.device];
    __weak typeof(SampuxEquipDetailViewController *) wSelf = self;
    _detailView.addOffViewBtnBlock = ^{
        [wSelf stateOffViewShow];
    };
    _detailView.removewOffViewBtnBlock = ^{
        [wSelf stateOffViewHide];
    };
}

- (void)settingBarBtnClick
{
    [self stateOffViewHide];
    SPEquipmentInstallViewController *installVC = [[SPEquipmentInstallViewController alloc]init];
    if (self.isConnectOrNot == YES) {
        installVC.model = [SPGetDeviceDetailValue getDetailData:self.device];
        //    installVC.model  = self.detailModel;
    }
    [self.navigationController pushViewController:installVC animated:YES];
}

- (void)stateOffViewShow
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
//    _nav.img.image = imageNamed(@"offImg");
//    _nav.img.image = imageNamed(@"nav");
    [self.view addSubview:self.stateOffView];
    _detailView.shutBtnOnHand.selected = YES;
    _detailView.shutBtnOnTime.selected = YES;
}

- (void)stateOffViewHide
{
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
//    _nav.img.image = imageNamed(@"nav");
    [self.stateOffView removeFromSuperview];
    _detailView.shutBtnOnHand.selected = NO;
    _detailView.shutBtnOnTime.selected = NO;
}

- (void)getStatus:(NSNotification *)notification
{
    [_backView.mj_header endRefreshing];

    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"getStatus == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00)
    {
        GBInterMaster_Bean_DeviceInfo13001 *device = [result objectForKey:@"device"];
        NSLog(@"device == %@",device);
        self.device = device;
        dispatch_async(dispatch_get_main_queue(), ^{
        [self createDetailView];
        });
        [self getData:device];
    } else {
        [SVProgressHUD showErrorWithStatus:@"获取最新状态失败"];
//        [MBProgressHUD showError:@"获取最新状态失败"];
    }
}

- (UIScrollView *)stateOffView
{
    if (_stateOffView == nil) {
        _stateOffView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
        [self createOffView];
    }
    return _stateOffView;
}

- (void)createOffView
{
    CGFloat font = 8.;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 16.;
    }
    
    _backView = [[UIScrollView alloc]initWithFrame:_stateOffView.bounds];
    _backView.backgroundColor = THBlackAlplaColor(0.9);
    [_stateOffView addSubview:_backView];
    _backView.alpha = 1;
    _backView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight);
    _backView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
//        UIButton *backBtn = [UIButton createButton];
//        [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
//        backBtn.frame = CGRectMake(10, 20, 40, 40);
//        [_backView addSubview:backBtn];
//        [backBtn setImage:[UIImage imageNamed:@"arrow_alpha"] forState:UIControlStateNormal];
//    
//        _titleLab = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/2 - Sampux6WScale(250)/2, 20, Sampux6WScale(250), 40)];
//        [_backView addSubview:_titleLab];
//        _titleLab.textColor = THWhiteAlplaColor(0.7);
//        _titleLab.textAlignment = NSTextAlignmentCenter;
//        _titleLab.text = self.titleStr;
//    
//        UIButton *settingBtn = [UIButton createButton];
//        [_backView addSubview:settingBtn];
//        [settingBtn setImage:imageNamed(@"setting") forState:UIControlStateNormal];
//        settingBtn.frame = CGRectMake(kScreenWidth - 10 - 40, 20, 40, 40);
//        [settingBtn addTarget:self action:@selector(settingBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *offBtnImg = [UIButton createButton];
    offBtnImg.frame = CGRectMake(_stateOffView.width/2 - Sampux6HScale(118/2)/2, _stateOffView.height * 0.3, Sampux6HScale(118/2), Sampux6HScale(118/2));
    [offBtnImg setBackgroundImage:imageNamed(@"shutdown") forState:UIControlStateNormal];
    [offBtnImg addTarget:self action:@selector(shutBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:offBtnImg];
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(self.view.width/2 - 60, offBtnImg.y - 50, 120, 40)];
    lab.textColor = THWhiteAlplaColor(0.6);
    lab.text = @"此设备已关机";
    lab.textAlignment = NSTextAlignmentCenter;
    lab.font = THFont(font + 2);
    [_backView addSubview:lab];
    
    _antifreezingBtn = [[SmapuxSettingUnitButton alloc]initWithFrame: CGRectMake(_backView.width/2- Sampux6WScale(70)/2, offBtnImg.bottom + Sampux6HScale(40), Sampux6WScale(140/2), Sampux6WScale(140/2))];
    _antifreezingBtn.titleLabel.font = THFont(font - 3);
    _antifreezingBtn.userInteractionEnabled = NO;
    [self.antifreezingBtn setTitle:@"防冻已开启" forState:UIControlStateNormal];
    [self.antifreezingBtn setImage:imageNamed(@"antifreeze") forState:UIControlStateNormal];
    [_backView addSubview:_antifreezingBtn];
    _antifreezingBtn.hidden = YES;
}

- (void)backBtnClick
{
    [self stateOffViewHide];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)settingBtnClick
{
    [self settingBarBtnClick];
}

- (void)shutBtnClick:(UIButton *)btn
{
    [self stateOffViewHide];
    self.detailModel.powerSwitchSetTime = [SampuxGetCurrentTime getCurrentTimeWithDate];
    _detailView.shutBtnOnHand.selected = NO;
    _detailView.shutBtnOnTime.selected = NO;

//    if (self.isConnectOrNot == NO) {
//        [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络设置"];
//    }else
//    {
        [GBInterMaster_CommForDeivce requestPowerSwitch:0 withDeviceAccount:self.detailModel.accountStr withPowerSwitch:1];
//    }
}

- (void)getData:(GBInterMaster_Bean_DeviceInfo13001 *)device
{
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5* NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
//        [_activity stopAnimating];
//    });
    SampuxListModel *model = [SPGetDeviceDetailValue getDetailData:device];
//    self.detailModel = model;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.detailView.model = model;
    });
    if (model.isShutDownOrNot) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stateOffViewShow];
        });
        if (model.isColdTempProtection) {
            self.antifreezingBtn.hidden = NO;
        }else
        {
            self.antifreezingBtn.hidden = YES;
        }
    }else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stateOffViewHide];
        });
    }
}


- (void)refreshData
{
    [GBInterMaster_CommForDeivce requestDeviceStatus:0 withDeviceAccount:self.detailModel.accountStr];
}

- (void)getNewStatus:(NSNotification *)notification
{
    SampuxListModel *model = self.detailView.model;
    NSLog(@"jdjjdd");
    
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"getNewStatus == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00)
    {
//        CGFloat getNewDate = [SampuxGetCurrentTime getCurrentTimeDate];
        GBInterMaster_Bean_DeviceInfo13001 *device = [result objectForKey:@"device"];
        if ([device.account isEqualToString:self.detailModel.accountStr])
        {
            if (fabs(model.workModeSetTime - device.workModeSetTime)<= 2 || fabs(model.heatModeSetTime -  device.heatModeSetTime)<= 2 || fabs(model.powerSwitchSetTime -  device.powerSwitchSetTime) <= 2|| fabs(model.currentSetTempeSetTime -  device.currentSetTempeSetTime) <= 2) {
            }else
            {
                self.device = device;
                [self getData:device];
            }//
        }
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"获取最新推送状态失败"];
//        [MBProgressHUD showError:@"获取最新推送状态失败"];
    }
}

- (void)setTitle:(NSNotification *)notification
{
    self.titleStr = notification.object;
}

- (void)createActivity
{
    _activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activity.frame = CGRectMake(0, 64, self.view.width, self.view.height - 64);
    [self.view addSubview:_activity];
    [_activity startAnimating];
    _activity.backgroundColor = THWhiteAlplaColor(1);
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3* NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
//        [_activity stopAnimating];
//    });
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self createAddBarBtnItem];
//    [self createActivity];
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
    _nav.titleStr = self.titleStr;
    _nav.button.hidden = NO;
    _nav.rightBtn.hidden = YES;
    self.rightBtn.hidden = NO;
    _titleLab.text = _nav.titleStr;
    [_detailView.header beginRefreshing];

    if (self.detailView.shutBtnOnHand.selected == YES ||self.detailView.shutBtnOnTime.selected == YES)
    {
        [self stateOffViewShow];
    }else
    {
        [self stateOffViewHide];
    }

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:NO];
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
    _nav.button.hidden = NO;
    _nav.rightBtn.hidden = YES;
    self.rightBtn.hidden = YES;
    [self stateOffViewHide];
    self.stateOffView = nil;
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.window willRemoveSubview:self.stateOffView];
    
    _nav.img.image = imageNamed(@"nav");
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
//    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
//    _nav.img.image = imageNamed(@"nav");
//    self.stateOffView = nil;

}

- (void)requestSwitch:(NSNotification *)notification
{
//    self.detailModel.powerSwitchSetTime = [SampuxGetCurrentTime getCurrentTimeWithDate];

    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"requestSwitch == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        //        [MBProgressHUD showError:@"设置开关机成功"];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setParameterSuccess" object:nil];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"设置开关机失败"];

//        [MBProgressHUD showError:@"设置开关机失败"];
    }
}

- (void)requestWorkMode:(NSNotification *)notification
{
//    self.detailModel.workModeSetTime = [SampuxGetCurrentTime getCurrentTimeWithDate];
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@" requestWorkMode == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        //        [MBProgressHUD showError:@"设置模式成功"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setParameterSuccess" object:nil];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"设置模式失败"];
//        [MBProgressHUD showError:@"设置模式失败"];
    }
}

- (void)requestHeatMode:(NSNotification *)notification
{
//    self.detailModel.heatModeSetTime = [SampuxGetCurrentTime getCurrentTimeWithDate];
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"requestHeatMode == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        //        [MBProgressHUD showError:@"设置加热模式成功"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setParameterSuccess" object:nil];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"设置加热模式失败"];

//        [MBProgressHUD showError:@"设置加热模式失败"];
    }
}

- (void)setTemp:(NSNotification *)notification
{
//    self.detailModel.currentSetTempeSetTime = [SampuxGetCurrentTime getCurrentTimeWithDate];
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"setTemp == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        
        //        [MBProgressHUD showError:@"设置温度成功"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setParameterSuccess" object:nil];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"设置温度失败"];

//        [MBProgressHUD showError:@"设置温度失败"];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
